{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "from pathlib import Path\n",
    "import json\n",
    "import geopandas as gpd\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.colors import ListedColormap\n",
    "import numpy as np"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 将GeoJSON转换为Shapefile",
   "id": "6dd50126f0b50b28"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 1. 定义文件路径\n",
    "json_path = Path('../data/json_file/新都区2021.json')\n",
    "shape_dir = Path('../data/shape_file')  # 建议使用目录而不是直接指定.shp文件\n",
    "shape_dir.mkdir(parents=True, exist_ok=True)  # 确保目录存在\n",
    "\n",
    "# 2. 读取JSON文件\n",
    "with open(json_path, 'r', encoding='utf-8') as f:\n",
    "    data = json.load(f)\n",
    "\n",
    "# 3. 将JSON数据转换为GeoDataFrame\n",
    "gdf = gpd.GeoDataFrame.from_features(data['features'])\n",
    "\n",
    "# 4. 设置坐标系（WGS84，EPSG:4326）\n",
    "gdf.crs = \"EPSG:4326\"\n",
    "\n",
    "# 5. 保存为Shapefile（只需指定目录或基础文件名）\n",
    "output_path = shape_dir / 'xinDu_2021_shp'  # 不写.shp扩展名，to_file会自动添加\n",
    "gdf.to_file(output_path, encoding='utf-8')\n",
    "\n",
    "print(f\"Shapefile已成功保存到: {output_path}\")"
   ],
   "id": "9df2d57ea9a817ee",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 读取并显示 Shapefile",
   "id": "459bf439541201ef"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 读取Shapefile\n",
    "shapefile_path = '../data/shape_file/xinDu_2021_shp/xinDu_2021_shp.shp'\n",
    "gdf = gpd.read_file(shapefile_path)\n",
    "\n",
    "# 查看数据前5行\n",
    "print(gdf.head())\n",
    "\n",
    "# # 基本绘图\n",
    "# gdf.plot()\n",
    "# plt.title(\"中国省级行政区划\")\n",
    "# plt.show()"
   ],
   "id": "7960fc735b42be97",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 1. 基础设置\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体\n",
    "plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题\n",
    "\n",
    "# 2. 创建专业级地图\n",
    "fig, ax = plt.subplots(figsize=(16, 12), dpi=300)\n",
    "\n",
    "# 3. 自定义配色方案（使用连续色阶）\n",
    "cmap = plt.get_cmap('viridis')\n",
    "num_provinces = len(gdf)\n",
    "colors = cmap(np.linspace(0, 1, num_provinces))\n",
    "\n",
    "# 4. 绘制省级行政区划\n",
    "gdf.plot(\n",
    "    ax=ax,\n",
    "    column='name',  # 按省份名称着色\n",
    "    categorical=True,\n",
    "    cmap=ListedColormap(colors),\n",
    "    edgecolor='black',\n",
    "    linewidth=0.8,\n",
    "    alpha=0.8,\n",
    "    legend=True,\n",
    "    legend_kwds={\n",
    "        'title': '省级行政区',\n",
    "        'loc': 'lower left',\n",
    "        'bbox_to_anchor': (1, 0.3),\n",
    "        'ncol': 2,\n",
    "        'fontsize': 8\n",
    "    }\n",
    ")\n",
    "\n",
    "# 5. 添加省会城市标记（使用center字段）\n",
    "for idx, row in gdf.iterrows():\n",
    "    if row['center'] and isinstance(row['center'], list):\n",
    "        ax.plot(\n",
    "            row['center'][0],\n",
    "            row['center'][1],\n",
    "            marker='o',\n",
    "            markersize=6,\n",
    "            color='red',\n",
    "            alpha=0.7\n",
    "        )\n",
    "        # 添加省会标签\n",
    "        ax.text(\n",
    "            row['center'][0] + 0.3,\n",
    "            row['center'][1] + 0.2,\n",
    "            row['name'],\n",
    "            fontsize=9,\n",
    "            color='darkred',\n",
    "            weight='bold'\n",
    "        )\n",
    "\n",
    "# 6. 地图装饰元素\n",
    "ax.set_title('中华人民共和国省级行政区划图', fontsize=18, pad=20)\n",
    "ax.set_xlabel('经度', fontsize=12)\n",
    "ax.set_ylabel('纬度', fontsize=12)\n",
    "\n",
    "# 7. 添加比例尺和指北针\n",
    "x_min, y_min, x_max, y_max = gdf.total_bounds\n",
    "scale_x = x_min + 0.1 * (x_max - x_min)\n",
    "scale_y = y_min + 0.1 * (y_max - y_min)\n",
    "ax.plot([scale_x, scale_x + 5], [scale_y, scale_y], color='black', linewidth=2)\n",
    "ax.text(scale_x + 2.5, scale_y - 0.5, '5°', ha='center')\n",
    "\n",
    "# 8. 优化显示\n",
    "ax.grid(True, linestyle='--', alpha=0.5)\n",
    "plt.tight_layout()\n",
    "\n",
    "# 9. 保存高质量输出\n",
    "# plt.savefig('./data/china_provinces_map.png', bbox_inches='tight', dpi=300)\n",
    "plt.show()"
   ],
   "id": "7aabfda3f5092207",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "id": "dd0292a874b3a05d",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
